package com.zt.english.receiver

import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.util.Log

/**
 * 来电去电广播拦截接收
 */
class AudioBroadcastReceiver : BroadcastReceiver() {
    private val TAG = "TAG"
    private var incoming_number: String? = null
    private var incomingFlag = false
    override fun onReceive(context: Context?, intent: Intent?) {
        val action = intent?.action
        when (action){
            Intent.ACTION_NEW_OUTGOING_CALL -> {
                //拨打电话
                incomingFlag = false
                val phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER)
                Log.i(TAG, "call OUT:$phoneNumber")
            }else->{
                //如果是来电
                val tm = context!!.getSystemService(Service.TELEPHONY_SERVICE) as TelephonyManager
                when (tm.callState) {
                    TelephonyManager.CALL_STATE_RINGING -> { //来电
                        incomingFlag = true //标识当前是来电
                        incoming_number = intent!!.getStringExtra("incoming_number")
                        Log.v(TAG, "RINGING :$incoming_number  "+ intent.dataString)
                    }
                    TelephonyManager.CALL_STATE_OFFHOOK -> if (incomingFlag) { //摘机（正在通话中）
                        Log.v(TAG, "incoming ACCEPT :$incoming_number")
                    }
                    TelephonyManager.CALL_STATE_IDLE -> if (incomingFlag) {//空闲
                        Log.v(TAG, "incoming IDLE")
                    }else{ //挂断
                        Log.v(TAG, "incoming other")
                    }
                }
            }
        }
    }
}